<template>
  <div class="container">
    <div class="myinfo">
      <el-descriptions class="margin-top" title="个人信息" :column="3" :size="size" style="margin: 20px 20px 24px 22px ;padding-top: 20px">
        <el-descriptions-item label="头像">
          <el-image
            style="width: 100px; height: 100px"
            :src="userData.imageUrl"
            :fit="fit"
          ></el-image>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" title="" :column="3" :size="size" style="margin: 20px 20px 24px 22px;">
        <el-descriptions-item label="姓名">{{userData.name}}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <template>
            <el-tag size="small">{{userData.sex == 1? '男' : '女'}}</el-tag>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{userData.phone}}</el-descriptions-item>
        <el-descriptions-item label="账号">{{userData.username}}</el-descriptions-item>
        <el-descriptions-item label="备注">
          <el-tag size="small">{{ userData.license}}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <div class="edit-button">
        <el-button type="primary" @click="isEditing = true">修改信息</el-button>
      </div>
    </div>
    <div v-if="isEditing" class="mapInfo" style="padding-top: 20px">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" size="medium" label-width="100px">
          <el-col :span="11">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="账号" prop="username">
              <el-input v-model="formData.username" placeholder="请输入单行文本" disabled="disabled" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                <!-- 注意：el-option 设置了 value 属性 -->
                <el-option v-for="(item, index) in sex" :key="index" :label="getLabel(item)" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="职业" prop="license">
              <el-input v-model="formData.license" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row>
        <!--              action="http://127.0.0.1:8888/userImage"-->
          <div class="custom-upload-container">
            <div class="upload-title">头像上传</div>
            <el-upload
              :action="baseURL + '/image/userImage'"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </div>
      </el-row>
      <div slot="footer" class="dialog-footer" style="padding-top: 50px">
        <el-button type="" style="" @click="handleFulsh">重置</el-button>
        <el-button type="primary" @click="handleEdit">确 定</el-button>
        <el-button type="warning" @click="isEditing = false">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/api/request'
import { myInfo } from '@/api/myinfo'
import { mapGetters } from 'vuex'// mapMutations
export default {
  data () {
    return {
      isEditing: false,
      dialogVisible: false,
      dialogImageUrl: '',
      imageUrl: '',
      formData: {
        imageUrl: ''
      },
      userData: {
        imageUrl: ''
      },
      baseURL: '',
      sex: [
        { value: 1, label: '男' },
        { value: 0, label: '女' }
      ]
    }
  },
  computed: {
    ...mapGetters(['isLogin', 'username', 'userToken'])
  },
  created () {
    this.userinfo()
    this.baseURL = this.$requestcode.defaults.baseURL
  },
  methods: {
    getLabel (item) {
      // 这个函数应该根据数据库的值返回对应的标签，例如 "男" 或 "女"
      if (item.value === 1) {
        return '男'
      } else {
        return '女'
      }
    },
    async userinfo () {
      const username = JSON.parse(localStorage.getItem('username'))
      try {
        await myInfo(username).then(resp => {
          if (resp.data.code === 200) {
            this.userData = resp.data.data
            this.formData = resp.data.data
          }
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.formData.imageUrl = res.data
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleFulsh () {
      this.userinfo()
    },
    handleEdit () {
      // const data = this.$cookies.get('rememberMe')
      const token = localStorage.getItem('token')
      request.put('/user/infos', this.formData, {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + token
        }
      }).then((resp) => {
        this.dialogFormVisible = false
        if (resp.data.flag === true) {
          this.$message({
            message: resp.data.message,
            type: 'success',
            center: true
          })
          this.isEditing = false
          // this.setRememberMeCookie(resp.data.data)
          this.$eventBus.$emit('user-info-updated')
        } else {
          this.$message({
            message: resp.data.message,
            type: 'error',
            center: true
          })
          // this.$message.error(resp.data.message)
        }
      })
        .catch(error => {
          // console.error('Error:', error)
          this.handleAxiosError(error)
        })
    },
    handleAxiosError (err) {
      if (err.isAxiosError && err.response) {
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  white-space: nowrap;
}

.myinfo {
  footnote-display: block;
  justify-content: space-between;
  align-items: flex-start; /* 垂直对齐到顶端 */
  margin: 10px 10px 0px 2px;
  width: 600px;
  height: 500px;
  background-color: #fcfcfc;
  white-space: nowrap;
}

.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 28px;
}

.el-descriptions-item {
  display: flex;
  align-items: center;
}

.mapInfo {
  margin: 10px 10px 0px 2px;
  width: 590px;
  height: 480px;
  background-color: #f5f2f2;
}

.upload-title {
  margin-right: 9px;
  white-space: nowrap;
}
.edit-button {
  padding-top: 130px;
}
</style>
